package com.example.movie.vm

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.blankj.utilcode.util.ToastUtils.cancel
import com.example.common.entity.MovieVideoEntity
import com.example.common.vm.BaseViewModel
import com.example.movie.api.MovieServerApi
import com.example.movie.intent.MovieViewIntent
import com.example.movie.repo.MoviePagingSource
import com.example.movie.repo.MovieRepository
import com.example.movie.state.MovieUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.Flow
import retrofit2.Retrofit
import javax.inject.Inject

@HiltViewModel
class MovieViewModel : BaseViewModel<MovieViewIntent>(){
    private val repository: MovieRepository = MovieRepository()
    private val _uiStateFlow = MutableSharedFlow<MovieUiState>()
    val uiStateFlow : SharedFlow<MovieUiState> = _uiStateFlow.asSharedFlow()
    var apiMovieServerApi :MovieServerApi
    init {
        apiMovieServerApi = repository.createApiServer()
    }

    override fun dispatchIntent(intent: MovieViewIntent) {
        when(intent){
            is MovieViewIntent.LoadLeverOneType -> loadLeverOneType()
            is MovieViewIntent.LoadLeverTwoType -> loadLeverTwoType(intent.pid)
        }
    }

    private fun loadLeverTwoType(pid: Int) {
        mViewModelScope.launch(mDispatcher){
            try {
                repository.getMutilTypeById(pid).collectLatest{
                    if (!it.isNullOrEmpty()){
                        _uiStateFlow.emit(MovieUiState.LoadLeverTwoTypeSuccess(it))
                    }else{
                        _uiStateFlow.emit(MovieUiState.LoadLeverTwoTypeFail("获取二级分类失败！"))
                    }
                }
            } catch (e: Exception) {
                _uiStateFlow.emit(MovieUiState.LoadLeverTwoTypeFail("获取二级分类失败！"))
            } finally {
                //取消协程
                cancel()
            }
        }
    }

    private fun loadLeverOneType() {
        mViewModelScope.launch(mDispatcher){
            try {
                repository.getMutilType().collectLatest {
                    if (!it.isNullOrEmpty()){
                        _uiStateFlow.emit(MovieUiState.LoadLeverOneTypeSuccess(it))
                    }else{
                        _uiStateFlow.emit(MovieUiState.LoadLeverOneTypeFail("获取一级分类失败！"))
                    }

                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiStateFlow.emit(MovieUiState.LoadLeverOneTypeFail("获取一级分类失败！"))
            } finally {
                cancel()
            }
        }
    }

    /**
     * 获取推荐电影视频
     */
    fun loadRecommendMovieVideo(): Flow<PagingData<MovieVideoEntity>> {
        return Pager(
            config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false),
            pagingSourceFactory = { MoviePagingSource(apiMovieServerApi) }).flow.cachedIn(mViewModelScope)
    }

    /**
     * 获取二级分类下的电影视频
     */
    fun loadMutilMovieVideo(typeId: Int): Flow<PagingData<MovieVideoEntity>>{
        return Pager(
            config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false),
            pagingSourceFactory = { MoviePagingSource(apiMovieServerApi, typeId)}).flow.cachedIn(mViewModelScope)
    }


}